using System;
using System.IO;
using UnityEngine;
using LS.Digitize;

namespace LS.Digitize
{
    public sealed class BoundsIntSerializer: CompoundSerializer<BoundsInt>
    {
        public BoundsIntSerializer() : base(typeof(BoundsInt),typeof(Vector3Int))
        {
            
        }
        
        public override void WriteData(IWriter writer, BoundsInt obj)
        {
            ISerializer subSerializer = SubSerializer;
            BoundsInt target = obj;
            using (writer.WriteObjectScope())
            {
                if (subSerializer is CompoundSerializer<Vector3Int> cs)
                {
                    using (writer.WritePropertyScope("position"))
                    {
                        cs.WriteData(writer,target.position);
                    }
                    using (writer.WritePropertyScope("size"))
                    {
                        cs.WriteData(writer,target.size);
                    }
                }
                else
                {
                    using (writer.WritePropertyScope("position"))
                    {
                        subSerializer.Write(writer,target.position);
                    }
                    using (writer.WritePropertyScope("size"))
                    {
                        subSerializer.Write(writer,target.size);
                    }
                }
            }
        }

        public override BoundsInt ReadData(IReader reader)
        {
            ISerializer subSerializer = SubSerializer;
            BoundsInt target = default;
            using (var objScope = reader.ReadObjectScope())
            {
                string propertyName = null;
                if (subSerializer is CompoundSerializer<Vector3Int> ps)
                {
                    propertyName = reader.ReadPropertyName();
                    Vector3Int position = ps.ReadData(reader);
                    propertyName = reader.ReadPropertyName();
                    Vector3Int size = ps.ReadData(reader);
                    target = new BoundsInt(position, size);
                }
                else
                {
                    propertyName = reader.ReadPropertyName();
                    Vector3Int position = (Vector3Int)subSerializer.Read(reader);
                    propertyName = reader.ReadPropertyName();
                    Vector3Int size = (Vector3Int)subSerializer.Read(reader);
                    target = new BoundsInt(position, size);
                }
            }

            return target;
        }
        
        public override void ReadInto(IReader reader, ref BoundsInt obj)
        {
            obj = ReadData(reader);
        }
    }
}